﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using HorseRaceTracker.Domain.Core;

namespace HorseRaceTracker.Infrastructure.ADO.NET
{
    public class HorseFetcher
    {

        
        public IEnumerable<Horse> GetAllHorses()
        {
            var countryFetcher = new CountryFetcher();
            var list = new List<Horse>();
            using (var sqlConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DataServices"].ConnectionString))
            {
                sqlConnection.Open();
                using (var cmd = new SqlCommand("SELECT HorseId,HorseName,BredIn,Sex,Birthyear,Trainer FROM  Horse", sqlConnection))
                {
                    using (var reader = cmd.ExecuteReader(CommandBehavior.Default))
                    {
                        if (reader != null)
                        {
                            while(reader.Read())
                            {
                               
                                var horse = new Horse( reader.GetGuid((int) HorseOrdinal.HorseId));
                                horse.BirthYear = reader.GetInt16((int) HorseOrdinal.Birthyear);
                                horse.BredIn = countryFetcher.RetrieveByCode(reader.GetString((int)HorseOrdinal.BredIn));
                                horse.Name = reader.GetString((int) HorseOrdinal.HorseName);
                                horse.Sex = ConvertToGender(reader.GetString((int)HorseOrdinal.Sex));
                                list.Add(horse);
                            }
                        }
                    }
                }

            }
            return list;

        }

        private static Gender ConvertToGender(string sex)
        {
            Gender gender;
            switch (sex.ToUpperInvariant())
            {
                case "M":
                    gender= Gender.Male;
                    break;
                case "F":
                    gender= Gender.Filly;
                    break;
                case "G":
                      gender= Gender.Filly;
                    break;
                default:
                    gender= Gender.Unknown;
                    break;
            }
            return gender;
        }
        private enum HorseOrdinal
        {
            HorseId = 0,
            HorseName = 1,
            BredIn = 2,
            Sex = 3,
            Birthyear = 4,
            Trainer = 5
        }
    }
}
